package com.lujieni.springbootrocketmq.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lujieni.springbootrocketmq.dto.OrderDTO;
import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;

@RocketMQTransactionListener
@RequiredArgsConstructor
public class TransactionListenerImpl implements RocketMQLocalTransactionListener {

    private ObjectMapper objectMapper = new ObjectMapper();

    private final DepartmentService departmentService;

    /**
     * 半事务消息发送成功后,执行本地事务的方法
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        try {
            String s = new String((byte[]) msg.getPayload());
            OrderDTO orderDTO = objectMapper.readValue(s, OrderDTO.class);
            // 执行本地业务逻辑（如数据库操作）
            System.out.println("执行本地事务，消息内容: " + orderDTO);
            // 模拟业务处理
            boolean success = doBusiness();
            
            if (success) {
                // 本地事务成功，提交消息
                return RocketMQLocalTransactionState.COMMIT;
            } else {
                // 本地事务失败，回滚消息
                return RocketMQLocalTransactionState.ROLLBACK;
            }
        } catch (Exception e) {
            // 异常情况返回未知状态，等待检查
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }

    /**
     * 检查本地事务状态
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        // 检查本地事务是否成功完成
        System.out.println("检查本地事务状态，消息内容: " + msg.getPayload());

        // 根据实际情况返回状态
        boolean isSuccess = checkBusinessStatus();
        
        if (isSuccess) {
            return RocketMQLocalTransactionState.COMMIT;
        } else {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
    
    private boolean doBusiness() {
        // 实际业务逻辑
        departmentService.insertBatch();
        return true; // 模拟成功
    }
    
    private boolean checkBusinessStatus() {
        // 检查业务状态
        return true; // 模拟成功
    }
}